package cn.exrick.content.service.impl;

import cn.exrick.common.constant.CommonConstant;
import cn.exrick.common.exception.XmallException;
import cn.exrick.common.jedis.JedisClient;
import cn.exrick.common.pojo.DataTablesResult;
import cn.exrick.content.service.ContentService;
import cn.exrick.manager.dto.front.AllGoodsResult;
import cn.exrick.manager.mapper.*;
import cn.exrick.manager.pojo.*;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
public class ContentServiceImpl implements ContentService {

    private final static Logger log= LoggerFactory.getLogger(ContentServiceImpl.class);

    @Autowired
    private TbPanelContentMapper tbPanelContentMapper;
    @Autowired
    private TbItemMapper tbItemMapper;
    @Autowired
    private TbItemDescMapper tbItemDescMapper;
    @Autowired
    private JedisClient jedisClient;
    @Autowired
    private TbNavMapper tbNavMapper;
    @Autowired
    private TbItemCatMapper tbItemCatMapper;

    @Value("${PRODUCT_HOME}")
    private String PRODUCT_HOME;

    @Value("${PRODUCT_ITEM}")
    private String PRODUCT_ITEM;

    @Value("${RECOMEED_PANEL_ID}")
    private Integer RECOMEED_PANEL_ID;

    @Value("${THANK_PANEL_ID}")
    private Integer THANK_PANEL_ID;

    @Value("${RECOMEED_PANEL}")
    private String RECOMEED_PANEL;

    @Value("${THANK_PANEL}")
    private String THANK_PANEL;

    @Value("${ITEM_EXPIRE}")
    private int ITEM_EXPIRE;

    @Value("${HEADER_PANEL_ID}")
    private int HEADER_PANEL_ID;

    @Value("${HEADER_BANNER}")
    private String HEADER_BANNER;

    @Value("${HEADER_NAV}")
    private String HEADER_NAV;

    @Value("${IMAGE_ACCESS_URL}")
    private String imageUrl;

    @Override
    public int addPanelContent(TbPanelContent tbPanelContent) {

        tbPanelContent.setCreateTime(new Date());
        tbPanelContent.setUpdateTime(new Date());
        if(tbPanelContentMapper.insert(tbPanelContent)!=1){
            throw new XmallException("添加轮播图失败");
        }
        //同步轮播图缓存
        updateBannerListRedis();
        return 1;
    }

    @Override
    public List<TbPanelContent> getPanelContentList() {
        List<TbPanelContent> list;
        //查询缓存
        try{
            //有缓存则读取
            String json=jedisClient.get(HEADER_BANNER);
            if(json!=null){
                list = new Gson().fromJson(json, new TypeToken<List<TbPanelContent>>(){}.getType());
                log.info("读取了首页缓存");
                return list;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        //没有缓存
        list = tbPanelContentMapper.getPanelContentList();
        for(TbPanelContent content : list){
            content.setPicture(imageUrl + content.getPicture());
        }
        //把结果添加至缓存
        try{
            jedisClient.set(HEADER_BANNER, new Gson().toJson(list));
            log.info("添加了轮播图缓存");
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public int deletePanelContent(int id) {

        if(tbPanelContentMapper.deleteByPrimaryKey(id)!=1){
            throw new XmallException("删除轮播图失败");
        }
       
        updateBannerListRedis();
        return 1;
    }

    @Override
    public int updateContent(TbPanelContent tbPanelContent) {

        TbPanelContent old=getTbPanelContentById(tbPanelContent.getId());
        if(StringUtils.isBlank(tbPanelContent.getPicture())){
            tbPanelContent.setPicture(old.getPicture());
        }

        if(CommonConstant.BANNER_TYPE_ITEM == tbPanelContent.getType()){
            tbPanelContent.setUrl(null);
        }else if(CommonConstant.BANNER_TYPE_URL == tbPanelContent.getType()){
            tbPanelContent.setItemId(null);
        }else{
            tbPanelContent.setUrl(null);
            tbPanelContent.setItemId(null);
        }

        tbPanelContent.setCreateTime(old.getCreateTime());
        tbPanelContent.setUpdateTime(new Date());
        if(tbPanelContentMapper.updateByPrimaryKey(tbPanelContent)!=1){
            throw new XmallException("更新轮播图失败");
        }

        updateBannerListRedis();
        return 1;
    }

    @Override
    public TbPanelContent getTbPanelContentById(int id) {

        TbPanelContent tbPanelContent=tbPanelContentMapper.selectByPrimaryKey(id);
        if(tbPanelContent==null){
            throw new XmallException("通过id获取轮播图内容失败");
        }
        return tbPanelContent;
    }

    @Override
    public List<TbItem> getRecommendGoods() {
        List<TbItem> list = new ArrayList<>();
        //查询缓存
        try{
            //有缓存则读取
            String json=jedisClient.get(RECOMEED_PANEL);
            if(json!=null){
                list = new Gson().fromJson(json, new TypeToken<List<TbItem>>(){}.getType());
                log.info("读取了推荐板块缓存");
                return list;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        TbItemExample example = new TbItemExample();
        TbItemExample.Criteria criteria = example.createCriteria();
        criteria.andIsRecommendEqualTo(1);
        criteria.andSaleDateLessThanOrEqualTo(new Date());
        list = tbItemMapper.selectByExample(example);

        for(TbItem tbItem : list){
            String[] split = tbItem.getImage().split(",");
            List<String> images = new ArrayList<>(split.length);
            for(String image : split){
                images.add(imageUrl + image);
            }
            tbItem.setImage(images.get(0));
            tbItem.setImageList(images);
        }

        //把结果添加至缓存
        try{
            jedisClient.set(RECOMEED_PANEL, new Gson().toJson(list));
            log.info("添加了推荐板块缓存");
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public TbItem getGoodsDetail(Long id) {
        jedisClient.del(PRODUCT_ITEM+":"+id);
        //查询缓存
        try{
            //有缓存则读取
            String json=jedisClient.get(PRODUCT_ITEM+":"+id);
            if(json!=null){
                TbItem tbItem= new Gson().fromJson(json,TbItem.class);
                log.info("读取了商品"+id+"详情缓存");
                //重置商品缓存时间
                jedisClient.expire(PRODUCT_ITEM+":"+id,ITEM_EXPIRE);
                return tbItem;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        TbItem tbItem=tbItemMapper.selectByPrimaryKey(id);

        TbItemCat tbItemCat = tbItemCatMapper.selectByPrimaryKey(tbItem.getCid());
        tbItem.setCname(tbItemCat.getName());

        TbItemDesc tbItemDesc=tbItemDescMapper.selectByPrimaryKey(id);
        tbItem.setDesc(tbItemDesc.getItemDesc());

        String images[]=tbItem.getImage().split(",");
        tbItem.setImage(imageUrl + images[0]);
        List<String> list=new ArrayList();
        for(int i=0;i<images.length;i++){
            list.add(imageUrl + images[i]);
        }
        tbItem.setImageList(list);
        //无缓存 把结果添加至缓存
        try{
            jedisClient.set(PRODUCT_ITEM+":"+id,new Gson().toJson(tbItem));
            //设置过期时间
            jedisClient.expire(PRODUCT_ITEM+":"+id,ITEM_EXPIRE);
            log.info("添加了商品"+id+"详情缓存");
        }catch (Exception e){
            e.printStackTrace();
        }
        return tbItem;
    }

    @Override
    public AllGoodsResult getAllProduct(int page, int size, String sort, Long cid, String search,int priceGt, int priceLte) {

        AllGoodsResult allGoodsResult=new AllGoodsResult();
        //分页执行查询返回结果
        if(page<=0) {
            page = 1;
        }
        PageHelper.startPage(page,size);

        //判断条件
        String orderCol;
        String orderDir;
        if(sort.equals("1")){
            orderCol="price";
            orderDir="asc";
        }else if(sort.equals("-1")){
            orderCol="price";
            orderDir="desc";
        }else{
            orderCol="sale_date";
            orderDir="desc";
        }

        List<TbItem> tbItemList = tbItemMapper.selectItemFront(cid,search,orderCol,orderDir,priceGt,priceLte);
        PageInfo<TbItem> pageInfo=new PageInfo<>(tbItemList);
        for(TbItem tbItem : tbItemList){
            String[] split = tbItem.getImage().split(",");
            List<String> images = new ArrayList<>(split.length);
            for(String image : split){
                images.add(imageUrl + image);
            }
            tbItem.setImage(images.get(0));
            tbItem.setImageList(images);
        }

        allGoodsResult.setData(tbItemList);
        allGoodsResult.setTotal((int)pageInfo.getTotal());

        return allGoodsResult;
    }

    public void updateBannerListRedis() {

        try {
            jedisClient.del(HEADER_BANNER);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public List<TbNav> getNavList() {
        List<TbNav> list = new ArrayList<>();
        //查询缓存
        try{
            //有缓存则读取
            String json=jedisClient.get(HEADER_NAV);
            if(json!=null){
                list = new Gson().fromJson(json, new TypeToken<List<TbNav>>(){}.getType());
                log.info("读取了导航栏缓存");
                return list;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        TbNavExample example = new TbNavExample();
        example.setOrderByClause("sort_order asc");
        TbNavExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdIsNull();
        list = tbNavMapper.selectByExample(example);
        for(TbNav tbNav : list){
            example = new TbNavExample();
            TbNavExample.Criteria c = example.createCriteria();
            c.andParentIdEqualTo(tbNav.getId());
            List<TbNav> children = tbNavMapper.selectByExample(example);
            tbNav.setChildren(children);
        }

        //把结果添加至缓存
        try{
            jedisClient.set(HEADER_NAV, new Gson().toJson(list));
            log.info("添加了导航栏缓存");
        }catch (Exception e){
            e.printStackTrace();
        }

        return list;
    }

    @Override
    public void addNav(TbNav tbNav) {
        tbNav.setCreateTime(new Date());
        tbNav.setUpdateTime(new Date());
        if(tbNav.getIsParent() != null && tbNav.getIsParent()){
            tbNav.setType(null);
            tbNav.setParentId(null);
        }
        if(tbNavMapper.insert(tbNav)!=1){
            throw new XmallException("添加导航栏失败");
        }
        jedisClient.del(HEADER_NAV);
    }

    @Override
    public void updateNav(TbNav tbNav) {
        TbNav old = getNavById(tbNav.getId());
        tbNav.setCreateTime(old.getCreateTime());
        tbNav.setUpdateTime(new Date());
        if(tbNav.getIsParent() != null && tbNav.getIsParent()){
            tbNav.setType(null);
            tbNav.setParentId(null);
        }
        if(tbNavMapper.updateByPrimaryKey(tbNav)!=1){
            throw new XmallException("更新导航栏失败");
        }
        jedisClient.del(HEADER_NAV);
    }

    @Override
    public TbNav getNavById(Long id) {
        return tbNavMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<TbNav> getNavListByType(Integer type) {
        TbNavExample example = new TbNavExample();
        TbNavExample.Criteria criteria = example.createCriteria();
        criteria.andTypeEqualTo(type);
        return tbNavMapper.selectByExample(example);
    }

    @Override
    public void deleteNav(List<Long> ids) {
        if(CollectionUtils.isEmpty(ids)){
            return;
        }

        tbNavMapper.deleteNav(ids);
        jedisClient.del(HEADER_NAV);
    }

    @Override
    public DataTablesResult getNavList(int draw, int start, int length,String isParent,String type, String search, String orderCol, String orderDir) {
        DataTablesResult result=new DataTablesResult();

        //分页执行查询返回结果
        PageHelper.startPage(start/length+1,length);
        List<TbNav> list = tbNavMapper.selectNavByCondition(isParent,type,search,orderCol,orderDir);
        PageInfo<TbNav> pageInfo=new PageInfo<>(list);
        result.setRecordsFiltered((int)pageInfo.getTotal());
        result.setRecordsTotal((int)pageInfo.getTotal());

        result.setDraw(draw);
        result.setData(list);

        return result;
    }
}
